import Page from "@/components/page";
import PageNav from "@/components/pageNav";
import http from "@/request";
import { View, Text } from "@tarojs/components";
import Taro from "@tarojs/taro";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { billType } from "@/types";
import { MoneyFormat } from "@/utils/format";
import categorys from "@/store/categorys";
import moment from "moment";
import { eventBus } from '@/event-bus';

import "./index.scss"
import account from "@/store/account";
import BillForm from "@/components/billForm";
import viewMode from "@/store/viewMode";
import { ShowToast } from "@/utils";

const BillDetail: React.FC = () => {
    const [billInfo, setBillInfo] = useState<billType>()
    const [formVisible, setFormVisible] = useState<boolean>(false)
    const loadBillInfo = (id) => {
        http.get(`/bills/detail/${id}`).then(res => {
            setBillInfo(res.data)
        })
    }

    const accountName = useMemo(() => {
        return (account?.accountList || []).find(item => {
            return item.id === billInfo?.accountId
        })?.name
    }, [billInfo, account.accountList])

    const getUserName = useCallback((userId) => {
        let userName
        const curAccount = (account?.accountList || []).find(item => {
            return item.id === billInfo?.accountId
        })
        if (curAccount) {
            userName = (curAccount?.members || []).find(item => {
                return item.userId === userId
            })?.userName
        }
        return userName || ''
    }, [billInfo, account.accountList])

    const handleDelete = () => {
        Taro.showModal({
            title: '是否删除当前账单？',
            content: '',
            success: (res: any) => {
                if (res.confirm) {
                    http.delete(`/bills/delete/${billInfo?.id}`).then(() => {
                        ShowToast("删除成功")
                        Taro.navigateBack()
                        eventBus.emit('refreshBillListEvent');
                    }).catch(err => {
                        ShowToast(err.msg || '删除失败')
                    })
                }
            }
        })
    }

    const closeModal = () => {
        setFormVisible(false)
    }
    const refresh = () => {
        setFormVisible(false)
        loadBillInfo(billInfo?.id)
        eventBus.emit('refreshBillListEvent');
    }
    
    useEffect(() => {
        viewMode.setBehind(formVisible)
    }, [formVisible])
    Taro.useLoad(({ id }) => {
        if (id) {
            loadBillInfo(id)
        }
    })
    return (
        <Page className="bills-detail-page card-background text-main-color flex-column flex-item">
            <PageNav showBack className="report-page-header need-filter">账单详情</PageNav>
            <View className="page-body border-main-color flex1">
                <View className="bill-detail-card page-background need-filter need-filter">
                    <View className={`bill-amount form-line-container ${billInfo?.type ? 'income' : 'pay'}`}>{MoneyFormat(billInfo?.amount)}</View>
                    <View className="form-line-container">
                        <View className="bill-info-item flex-row flex-item">
                            <View className="bill-info-label">账单备注：</View>
                            <View className="bill-info-value">{billInfo?.note}</View>
                        </View>
                    </View>
                    <View className="form-line-container">
                        <View className="bill-info-item flex-row flex-item">
                            <View className="bill-info-label">账单分类：</View>
                            <View className="bill-info-value">{categorys?.categoryMap && categorys?.categoryMap[billInfo?.category || '']?.name}</View>
                        </View>
                    </View>
                    <View className="form-line-container">
                        <View className="bill-info-item flex-row flex-item">
                            <View className="bill-info-label">收支类型：</View>
                            <View className="bill-info-value">{billInfo?.type ? '收入' : '支出'}</View>
                        </View>
                    </View>
                    <View className="form-line-container">
                        <View className="bill-info-item flex-row flex-item">
                            <View className="bill-info-label">账单日期：</View>
                            <View className="bill-info-value">{moment(billInfo?.date).format('YYYY-MM-DD')}</View>
                        </View>
                    </View>
                    <View className="form-line-container">
                        <View className="bill-info-item flex-row flex-item">
                            <View className="bill-info-label">归属账本：</View>
                            <View className="bill-info-value">{accountName}</View>
                        </View>
                    </View>
                    <View className="form-line-container">
                        <View className="bill-info-item flex-row flex-item">
                            <View className="bill-info-label">付款成员：</View>
                            <View className="bill-info-value">{getUserName(billInfo?.userId)}</View>
                        </View>
                    </View>
                    {
                        billInfo?.type === 2 ? <View className="form-line-container">
                            <View className="bill-info-item flex-row flex-item">
                                <View className="bill-info-label">收款成员：</View>
                                <View className="bill-info-value">{getUserName(billInfo?.payeeId)}</View>
                            </View>
                        </View> : null
                    }
                </View>
            </View>
            <View className="page-bottom flex-column flex-item card-background">
                <View className="half-line"></View>
                <View className="comment-input-container flex-row flex-item">
                    <View className="flex1"></View>
                    <View onClick={handleDelete} className="btn font-size24 preview-btn flex-row flex-center">
                        <Text className="data-val font-size24">删 除</Text>
                    </View>
                    <View className="flex1"></View>
                    <View onClick={() => setFormVisible(true)} className="btn font-size24 save-btn flex-row flex-center">
                        <Text className="data-val font-size24">编 辑</Text>
                    </View>
                    <View className="flex1"></View>
                </View>
            </View>
            <BillForm
                visible={formVisible}
                onClose={closeModal}
                onSure={refresh}
                bill={billInfo}>
            </BillForm>
        </Page>
    )
}

export default BillDetail